<template>
  <a-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    :confirm-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
  >
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-row :gutter="20">
          <a-col :sm="24" :md="24" :xl="24">
            <a-form-model
              layout="inline"
              ref="myForm"
              :rules="validatorRules"
              :model="form"
              :label-col="{ style: { width: '150px' } }"
            >
              <a-row :gutter="24">
                <a-col :sm="24" :md="24" :xl="24">
                  <a-form-model-item label="网点区域" prop="networkId">
                    <a-row :gutter="5">
                      <a-col :span="5">
                        <a-select
                          placeholder="请选择省"
                          v-model="form.provinceCode"
                          @change="(e, data) => addressChange(e, 'cityOptions', 'province', data.key)"
                        >
                          <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code">
                            {{ item.name }}
                          </a-select-option>
                        </a-select>
                      </a-col>
                      <a-col :span="5">
                        <a-select
                          placeholder="请选择市"
                          v-model="form.cityCode"
                          @change="(e, data) => addressChange(e, 'areaOptions', 'city', data.key)"
                        >
                          <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">
                            {{ item.name }}
                          </a-select-option>
                        </a-select>
                      </a-col>
                      <a-col :span="5">
                        <a-select
                          placeholder="请选择区"
                          v-model="form.areaCode"
                          @change="(e, data) => addressChange(e, 'streetOptions', 'area', data.key)"
                        >
                          <a-select-option v-for="item in areaOptions" :key="item.name" :value="item.code">
                            {{ item.name }}
                          </a-select-option>
                        </a-select>
                      </a-col>
                      <a-col :span="5">
                        <a-select
                          placeholder="请选择街道"
                          v-model="form.streetCode"
                          @change="(e, data) => addressChange(e, '', 'street', data.key)"
                        >
                          <a-select-option v-for="item in streetOptions" :key="item.name" :value="item.code">
                            {{ item.name }}
                          </a-select-option>
                        </a-select>
                      </a-col>
                      <a-col :span="4">
                        <a-select
                          placeholder="请选择网点"
                          v-model="form.networkId"
                          @change="
                            () => {
                              $refs.myForm.validateField('networkId')
                            }
                          "
                        >
                          <a-select-option
                            v-for="item in networkOptions"
                            :key="parseInt(item.code)"
                            :value="parseInt(item.code)"
                          >
                            {{ item.name }}
                          </a-select-option>
                        </a-select>
                      </a-col>
                    </a-row>
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="主板ID" prop="mainboardId">
                    <a-input allowClear class="per100" placeholder="请输入" v-model="form.mainboardId" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="地点" prop="subject">
                    <a-input allowClear placeholder="请输入" v-model="form.subject" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="设备别名" prop="deviceName">
                    <a-input allowClear placeholder="请输入" v-model="form.deviceName" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="设备类型" prop="deviceType">
                    <j-dict-select-tag
                      v-model="form.deviceType"
                      @input="
                        () => {
                          $refs.myForm.validateField('deviceType')
                        }
                      "
                      placeholder="请选择"
                      dictCode="deviceType"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="格子类型" prop="cellType">
                    <j-dict-select-tag
                      v-model="form.cellType"
                      @input="
                        () => {
                          $refs.myForm.validateField('cellType')
                        }
                      "
                      placeholder="请选择"
                      dictCode="cellType"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="物联网卡激活日期" prop="networkCardActiveTime">
                    <a-date-picker class="per100" v-model="form.networkCardActiveTime" valueFormat="YYYY-MM-DD" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="设备出售时间" prop="equipmentSalesTime">
                    <a-date-picker class="per100" v-model="form.equipmentSalesTime" valueFormat="YYYY-MM-DD" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="计费方式" prop="billingMethod">
                    <j-dict-select-tag
                      @input="
                        () => {
                          $refs.myForm.validateField('billingMethod')
                        }
                      "
                      v-model="form.billingMethod"
                      placeholder="请选择"
                      dictCode="billingMethod"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="是否存手机" prop="saveMobile">
                    <j-dict-select-tag
                      v-model="form.saveMobile"
                      @input="
                        () => {
                          $refs.myForm.validateField('saveMobile')
                        }
                      "
                      placeholder="请选择"
                      dictCode="userYn"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="是否支持中途取包" prop="midwayPick">
                    <j-dict-select-tag
                      v-model="form.midwayPick"
                      @input="
                        () => {
                          $refs.myForm.validateField('midwayPick')
                        }
                      "
                      placeholder="请选择"
                      dictCode="midwayPick"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12" v-if="form.midwayPick === '0'">
                  <a-form-model-item label="中途取包次数" prop="midwayPickTimes">
                    <a-input-number class="per100" placeholder="请输入" v-model="form.midwayPickTimes" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="设备状态" prop="equipmentStatus">
                    <j-dict-select-tag
                      @input="
                        () => {
                          $refs.myForm.validateField('equipmentStatus')
                        }
                      "
                      v-model="form.equipmentStatus"
                      placeholder="请选择"
                      dictCode="equipmentStatus"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12">
                  <a-form-model-item label="是否定时清箱">
                    <j-dict-select-tag v-model="form.clearContainer" placeholder="请选择" dictCode="clearContainer" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12" v-if="parseInt(form.clearContainer) === 1">
                  <a-form-model-item label="定时清箱周期">
                    <a-input placeholder="请输入天数" class="per100" v-model="form.taskCycle" addon-after="天" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12" v-if="parseInt(form.clearContainer) === 1">
                  <a-form-model-item label="任务时间">
                    <a-time-picker class="per100" v-model="form.taskTime" format="HH:mm" valueFormat="HH:mm" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12" v-if="!isBusiness">
                  <a-form-model-item label="是否隐藏">
                    <j-dict-select-tag allowClear v-model="form.hideStatus" placeholder="请选择" dictCode="hidden" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12" v-if="showHiddenOption">
                  <a-form-model-item label="逻辑时间(分钟)">
                    <a-input allowClear v-model="form.logicTime" placeholder="时间" />
                  </a-form-model-item>
                </a-col>
                <a-col :sm="24" :md="24" :xl="12" v-if="showHiddenOption">
                  <a-form-model-item label="逻辑单数(单)">
                    <a-input allowClear v-model="form.logicOrderNum" placeholder="单数" />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </a-col>
        </a-row>
      </div>
    </a-card>
  </a-modal>
</template>

<script>
import Api from '@/api/DeviceManage/DeviceList'
import CommonApi from '@/api/Common/index'
import { httpAction, getAction } from '@/api/manage'
import { cloneObject, validateDuplicateValue } from '@/utils/util'
import { RoleMixin } from '@/mixins/roleUtil'

export default {
  name: 'DeviceAdd',
  inject: ['closeCurrent'],
  mixins: [RoleMixin],
  data() {
    return {
      defaultData: {
        id: 0,
        provinceCode: undefined, // 省
        cityCode: undefined, // 市
        areaCode: undefined, // 区
        streetCode: undefined, // 镇
        networkId: undefined, // 网点
        businessId: undefined, // 商家id
        mainboardId: '', // 主板id
        deviceName: 'A区', // 设备别名
        deviceType: 1, // 设备类型
        cellType: 0, // 格子类型
        subject: '', //项目
        cellNum: undefined, // 格子数量
        simMsg: '', // SIM卡信息
        networkCardNum: '', // 物联网卡卡号
        networkCardActiveTime: new Date(), // 物联网卡激活日期
        equipmentSalesTime: new Date(), // 设备出售时间
        warrantyPeriod: undefined, // 保修周期(月)
        billingMethod: '1', // 计费方式
        saveMobile: '0', // 是否存手机
        midwayPick: '0', // 是否支持中途取包
        midwayPickTimes: 4,
        advertisingScreen: undefined, // 是否带广告屏
        displayBrightness: undefined, // 显示亮度
        volume: undefined, // 音量
        equipmentStatus: 3, // 设备状态
        hideStatus: 1, // 是否隐藏
        clearContainer: 1, // 是否定时清箱
        latestCleaningTime: undefined, // 最新清箱时间
        taskCycle: 0,
        taskTime: '23:05', // 任务时间
        versionId: undefined, // 客户端版本号
      },
      form: {},
      title: '新增机器',
      loading: false,
      visible: false,
      modalWidth: '80%',
      provinceOptions: [],
      cityOptions: [],
      areaOptions: [],
      streetOptions: [],
      networkOptions: [],
      validatorRules: {
        networkId: [{ required: true, message: '网点不能为空', trigger: 'change' }],
        mainboardId: [
          { required: true, message: '主板ID不能为空', trigger: 'change' },
          {
            validator: (rule, value, callback) =>
              validateDuplicateValue('t_machine', 'mainboard_id', value, this.form.id, callback),
            trigger: 'blur',
          },
        ],
        deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
        deviceName: [{ required: true, message: '设备别名不能为空', trigger: 'change' }],
        cellType: [{ required: true, message: '格子类型不能为空', trigger: 'change' }],
        networkCardActiveTime: [{ required: true, message: '物联网卡激活日期不能为空', trigger: 'change' }],
        equipmentSalesTime: [{ required: true, message: '设备出售时间不能为空', trigger: 'change' }],
        billingMethod: [{ required: true, message: '计费方式不能为空', trigger: 'change' }],
        saveMobile: [{ required: true, message: '是否存手机不能为空', trigger: 'change' }],
        midwayPick: [{ required: true, message: '是否支持中途取包不能为空', trigger: 'change' }],
        equipmentStatus: [{ required: true, message: '设备状态不能为空', trigger: 'change' }],
        midwayPickTimes: [{ required: true, message: '中途取包次数不能为空', trigger: 'change' }],
      },
    }
  },
  created() {
    this.getAddress('provinceOptions')
  },
  computed: {
    showHiddenOption() {
      return !!this.form.hideStatus && Number(this.form.hideStatus || '') === 0 && !this.isBusiness
    },
  },
  methods: {
    // 获取地址
    getAddress(name, data) {
      getAction(CommonApi.addressList, data).then((res) => {
        this[name] = res.result
      })
    },
    // 地址改变
    addressChange(e, name, key, cn) {
      let obj = {}
      // 改变重置后面市区镇商家网点设备
      if (key === 'province') {
        obj = {
          cityCode: undefined,
          areaCode: undefined,
          streetCode: undefined,
          businessId: undefined,
          networkId: undefined,
          deviceId: undefined,
        }
        this.cityOptions = []
        this.areaOptions = []
        this.streetOptions = []
      } else if (key === 'city') {
        obj = {
          areaCode: undefined,
          streetCode: undefined,
          businessId: undefined,
          networkId: undefined,
          deviceId: undefined,
        }
        this.areaOptions = []
        this.streetOptions = []
      } else if (key === 'area') {
        obj = {
          streetCode: undefined,
          networkId: undefined,
          businessId: undefined,
          deviceId: undefined,
        }
        this.streetOptions = []
      } else if (key === 'street') {
        obj = {
          businessId: undefined,
          networkId: undefined,
          deviceId: undefined,
        }
      } else if (key === 'agentCode') {
        obj = {
          businessId: undefined,
          networkId: undefined,
          deviceId: undefined,
        }
      }

      this.networkOptions = []
      this.deviceOptions = []
      if (cn) {
        this.form = { ...this.form, ...obj }
      }
      if (name && e) {
        this.getAddress(name, { [`${key}Code`]: e })
        this.form[`${key}Cn`] = cn
      }
      // 区和镇改变重新请求商家
      if (key === 'province' || key === 'city' || key === 'area' || key === 'street') {
        if (e) {
          this.agentList('networkOptions', { [`${key}Code`]: e, type: 1 })
        }
      }
    },
    // 获取商家网点设备下拉列表
    agentList(name, data) {
      getAction(CommonApi.agentList, data).then((res) => {
        this[name] = res.result
      })
    },

    async showModal() {
      this.form = cloneObject(this.defaultData)
      this.visible = true
    },

    handleCancel() {
      this.visible = false
    },

    handleOk() {
      this.$refs.myForm.validate((valid) => {
        if (valid) {
          let url = Api.add
          let method = 'post'
          this.loading = true
          httpAction(url, this.form, method)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success(res.message)
                this.handleCancel()
                this.$emit('ok')
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
  },
}
</script>

<style scoped></style>

